import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os

def plot_results(capacity):
    # 读取结果
    df = pd.read_csv(f'data/results_{capacity}.csv')
    
    # 设置图表风格
    plt.style.use('seaborn')
    sns.set_palette("husl")
    
    # 创建图表
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
    
    # 绘制执行时间
    for algo in df['Algorithm'].unique():
        algo_data = df[df['Algorithm'] == algo]
        ax1.plot(algo_data['N'], algo_data['TimeTaken'], 
                marker='o', label=algo)
    
    ax1.set_xscale('log')
    ax1.set_yscale('log')
    ax1.set_xlabel('Number of Items (log scale)')
    ax1.set_ylabel('Execution Time (ms, log scale)')
    ax1.set_title(f'Execution Time vs Number of Items (Capacity = {capacity})')
    ax1.legend()
    ax1.grid(True)
    
    # 绘制内存使用
    for algo in df['Algorithm'].unique():
        algo_data = df[df['Algorithm'] == algo]
        ax2.plot(algo_data['N'], algo_data['MemoryUsed'], 
                marker='o', label=algo)
    
    ax2.set_xscale('log')
    ax2.set_yscale('log')
    ax2.set_xlabel('Number of Items (log scale)')
    ax2.set_ylabel('Memory Usage (bytes, log scale)')
    ax2.set_title(f'Memory Usage vs Number of Items (Capacity = {capacity})')
    ax2.legend()
    ax2.grid(True)
    
    # 调整布局
    plt.tight_layout()
    
    # 保存图表
    plt.savefig(f'report/performance_capacity_{capacity}.png')
    plt.close()

def main():
    # 创建report目录（如果不存在）
    os.makedirs('report', exist_ok=True)
    
    # 处理每个容量
    capacities = [10000, 100000, 1000000]
    for capacity in capacities:
        plot_results(capacity)
        
        # 生成统计报告
        df = pd.read_csv(f'data/results_{capacity}.csv')
        stats = df.groupby('Algorithm').agg({
            'TimeTaken': ['mean', 'std', 'min', 'max'],
            'MemoryUsed': ['mean', 'std', 'min', 'max']
        })
        
        # 保存统计报告
        stats.to_csv(f'report/stats_capacity_{capacity}.csv')

if __name__ == '__main__':
    main() 